#include "mainlogic.h"
#include <string.h>
#include "PID.h"
#include <math.h>
#include "kalman.h"
#include "ocxo_ct.h"
#include "ms1022.h"
#include "iirfilter.h"
#include "main.h"
#include "cmsis_os.h"
#include "tmp75.h"
#include "task.h"
#include "cmd.h"
#include "stm32f4xx_hal_dma.h"
#include "eeprom.h"
#include "spi_flash.h"
#include "config.h"
#include "Utility.h"
#include "DBG.h"

//#define SCAL 0.00097469593351704614*0.00095337764197749714 *0.0009376809551143783*0.00092939962337658714
extern TIM_HandleTypeDef htim2;
extern TIM_HandleTypeDef htim3;
extern TIM_HandleTypeDef htim5;
extern TIM_HandleTypeDef htim9;
extern TIM_HandleTypeDef htim1;
extern ADC_HandleTypeDef hadc1;

extern UART_HandleTypeDef huart1;
extern UART_HandleTypeDef huart6;
extern IWDG_HandleTypeDef hiwdg;

#define UART_GPS_BUF_SIZE 400
#define UART_GPS_DMA_BUF_SIZE 200
uint8_t uart_receive_buf[UART_GPS_DMA_BUF_SIZE];
uint8_t uart_receive_used[UART_GPS_BUF_SIZE];

uint8_t  uart_line[UART_GPS_DMA_BUF_SIZE+1];

#define UART_CMD_BUF_SIZE 400
#define UART_CMD_DMA_BUF_SIZE 200
uint8_t uart_cmd_receive_buf[UART_CMD_DMA_BUF_SIZE];
uint8_t uart_cmd_receive_used[UART_CMD_BUF_SIZE];

UartBuf cmdBuf;
UartBuf gpsBuf;
GpsStatus g_gpsStatus = {0};
ControllerStatus g_ctlStatus = {0};

int uart_lineIndex;
unsigned char showLog;

#define STORE_FLAG 0xE1E1E1E1

//Gps Info
uint16_t adcBuf[64];
uint8_t stepOK;
uint64_t totleCount;
int32_t preOffset = 0;
uint8_t gpsUpdated;
uint32_t tempSum;
uint32_t tempCount;
float  tempValue;
uint8_t ocxo_warm_ok = 0;
uint8_t init;
KalmanData kalman;
extern uint32_t tdcCounter;
uint32_t g_mcuTemp = 0;
uint8_t g_tdcReady = 0;
int32_t g_tdcOffset = 0;
int32_t g_tdcValue = 0;
int32_t g_ppsoff = 0;
int32_t g_ppspre = 0;

static int32_t preDacValue = 0;
static int32_t prePwmValue = 0;

void DacInit(void)
{
	if(g_Controller_config.version <= 2)
	{
		htim3.Instance->ARR = 10000;
    htim1.Instance->ARR = 1000;
	}
}

void setDacValue(int32_t value, uint8_t offsetModel) {
	int32_t pwmValue;
	int32_t offset = 20000;
	if(g_Controller_config.type == 0)
	{
		//不再支持
	}
	else
	{
		//high dac满度计数为1000(1khz)，low为10000（10khz)
		uint32_t rlValue = value;
		uint32_t high = rlValue / 1000;
		uint32_t low = rlValue % 1000;
		DBGI("org=%d high=%d low=%d temp=%.1f\n",value, high, low, g_ctlStatus.temp);
		
		if(offsetModel) {
			offset = (preDacValue) - (rlValue);
		}
		pwmValue = prePwmValue - offset;
		if(offsetModel && ABS(pwmValue)<9500 && ABS(pwmValue)>500){
			htim3.Instance->CCR1 = pwmValue;
			DBGI("pwm offset mode offset = %d pwm = %d\n",offset,pwmValue);
		}
		else {
			pwmValue = 5000+low;
			preDacValue = rlValue;
			prePwmValue = pwmValue;
			htim3.Instance->CCR1 = pwmValue;
			htim1.Instance->CCR1 = high;
		}
	}
}

void setDacValueDirect(int32_t high, uint32_t low) {
	if(g_Controller_config.type == 0)
	{
	}
	else
	{
		DBGI("high = %d low= %d\n", high, low);
		htim1.Instance->CCR1 = high;
		htim3.Instance->CCR1 = low;
	}
}

const osThreadAttr_t UartTask_attributes = {
  .name = "uartTask",
  .stack_size = 512,
  .priority = (osPriority_t) osPriorityNormal,
};
osThreadId_t UartTaskHandle;
void UartTask(void *argument);

const osThreadAttr_t TDCTask_attributes = {
  .name = "TDCTask",
  .stack_size = 128 * 4,
  .priority = (osPriority_t) osPriorityRealtime,
};
osThreadId_t tdcTaskHandle = NULL;
void TDCTask(void *argument);



void init_user(void) 
{
	uart_lineIndex = 0;
	g_gpsStatus.type = GpsFixTypeNone;
	g_gpsStatus.valid = 0;
	totleCount = 0;
	stepOK = 0;
	gpsUpdated = 0;
	showLog = 1;
	init = 1;
	tempSum = 0;
	tempCount = 0;
	g_tdcReady = 0;
	preOffset = 99999999;
	InitLogSystem();
	cmdBuf.lineStart = 0;
	cmdBuf.lineEnd = 0;
	cmdBuf.dmabuf = uart_cmd_receive_buf;
	cmdBuf.line = uart_cmd_receive_used;
	cmdBuf.dmabufLen = UART_CMD_DMA_BUF_SIZE;
	cmdBuf.lineLen = UART_CMD_BUF_SIZE;
	cmdBuf.readIdx = 0;
	gpsBuf.lineStart = 0;
	gpsBuf.lineEnd = 0;
	gpsBuf.dmabuf = uart_receive_buf;
	gpsBuf.line = uart_receive_used;
	gpsBuf.dmabufLen = UART_GPS_DMA_BUF_SIZE;
	gpsBuf.lineLen = UART_GPS_BUF_SIZE;
	gpsBuf.readIdx = 0;
	//1M clk
	HAL_TIM_Base_Start(&htim2);
	HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
	//1pps out
	HAL_TIM_Base_Start(&htim5);
	HAL_TIM_PWM_Start(&htim5, TIM_CHANNEL_2);
	//stop out
	if(g_Controller_config.type == 2)
	{
		HAL_TIM_Base_Start(&htim9);
		HAL_TIM_PWM_Start(&htim9, TIM_CHANNEL_1);
	}
	//DAC low
	HAL_TIM_Base_Start(&htim3);
	HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
	//DAC High
	HAL_TIM_Base_Start(&htim1);
	HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
	//PB15 pps in
	HAL_NVIC_SetPriority(EXTI15_10_IRQn, 4, 0);
  HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);
	
	tmp75_init();
	if(g_Controller_config.type == 2)
	{
		MS1022_Init();
	}
	printf("eeprom test\n");
	//
  if(AA24x_Test())
	{
		DBGI("eeprom test ok.\n");
	}
	else
	{
		DBGI("eeprom test failed.\n");
	}
	if(SPI_Flash_ReadFlashID())
	{
		DBGI("spi flash read ok.\n");
	}
	else
	{
		DBGI("spi test failed.\n");
	}
	g_Ocxo_info.dacValue = (500000);
  OcxoInfo_Load();
	//SPI_Flash_Test();
	//SPI_Flash_EraseTotal();
	
	DacInit();
	kalman.seconds = 0;
	kalmanInit(&kalman);
	//intOCXO_ct();
	//ocxo_spiflash_test();
	intOCXO_ct();
	
	//lea-8t 
	uint8_t send[] = {0xB5,0x62,0x06,0x01,0x03,0x00,0x0D,0x01,0x01,0x19,0x69};
	HAL_UART_Transmit(&huart6, (uint8_t *)&send, 11, 0xFFFF);
	uint8_t send2[] = {0xB5,0x62,0x06,0x3D,0x1C,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
	  ,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x51,0x01,0x00,0x01,0x00,0x00,0x00,0x33,0xC8};
	HAL_UART_Transmit(&huart6, (uint8_t *)&send2, 36, 0xFFFF);
	uint8_t send3[] = {0xB5 ,0x62 ,0x06 ,0x01 ,0x03 ,0x00 ,0xF0 ,0x03 ,0x00 ,0xFD ,0x15};
	HAL_UART_Transmit(&huart6, (uint8_t *)&send3, 11, 0xFFFF);
		//使用idle时需要关闭dma fifo
	HAL_UARTEx_ReceiveToIdle_DMA(&huart6,gpsBuf.dmabuf,gpsBuf.dmabufLen);
	HAL_UARTEx_ReceiveToIdle_DMA(&huart1,cmdBuf.dmabuf,cmdBuf.dmabufLen);
	UartTaskHandle = osThreadNew(UartTask, NULL, &UartTask_attributes);
	if(g_Controller_config.type == 2)
	{
		MS1022_NewMeasure();
	}
	HAL_PWR_EnableBkUpAccess();
}

void gpsUart_Process(void);

void UartTask(void *argument)
{
	for(;;)
	{
		uint32_t notify_val = 0;
		notify_val = ulTaskNotifyTake( (BaseType_t )pdTRUE,2000);
		if (notify_val != 0)
		{
			Uart_ReceiveProcess();
			gpsUart_Process();
		}
	}
}

void TDCTask(void *argument)
{
	for(;;)
	{

	}
}

void TDC_Task(void)
{
	static uint32_t tick = 0;
	static uint8_t first = 1;
	if(g_Controller_config.type == 2)
	{
		if(!(TDC_INT_GPIO_Port->IDR & TDC_INT_Pin))
		{
			unsigned char error = 0;
			unsigned char noint = 0;
			long reg = MS1022_DoMeasure(&error,&noint);
			if(error == 0)
			{
				if(!first)
				{
					int32_t offset = g_oc_status.preTdcValue - reg;
					float offsetps = offset * 3.0518;  // 200ns*1000ps/65535
					if(/*g_oc_status.controlCount >= 0 || */!ocxo_warm_ok)
					{
						DBGI("TDC = %d, of=%d pps=%d\n", reg>>16, offset, g_ppspre);
					}
					if(ocxo_warm_ok && !g_oc_status.offsetInvlid)
					{
						updateSensor(offsetps, 0);
					}
					g_oc_status.offsetInvlid = 0;
				}
				first = 0;
				g_oc_status.preTdcValue = reg;
			}
			tick = HAL_GetTick();
			MS1022_NewMeasure();
		}
		if((HAL_GetTick()-tick)>2000)
		{
			MS1022_NewMeasure();
			tick = HAL_GetTick();
			DBGI("new start\n");
		}
	}
	else {
		if(!ocxo_warm_ok)
		{
			return;
		}
		if(g_tdcReady)
		{
			//理论1us对应3v, ADC值3723.6*4=14894，1us=1000000ps/14894=67.145
			g_tdcReady = 0;
			float offsetps = g_tdcOffset * ADC2PS;
			float tdc = (8000-g_tdcValue);
			updateSensor(offsetps, tdc);
		}
	}
}

#define MAX_UART_LINE_SIZE 400  // 定义明确的缓冲区大小上限

void gpsUart_Process(void)
{
	static uint8_t isUbx = 0;
	static uint8_t ubxLen = 0;
	static uint32_t lastUpdate = 0;
	static uint8_t preOne = 0;
	
	// 添加缓冲区大小保护检查
	if (gpsBuf.line == NULL || gpsBuf.dmabuf == NULL) {
		return;  // 如果任何缓冲区未初始化，直接返回
	}
	uart_line[UART_GPS_DMA_BUF_SIZE] = 0;
	if(gpsBuf.lineEnd != gpsBuf.lineStart) 
	{
		uint16_t tmpEnd;
		__disable_irq();
		tmpEnd = gpsBuf.lineEnd;
		__enable_irq();
		while(tmpEnd != gpsBuf.lineStart)
		{
			// 安全访问gpsBuf.line，确保索引有效
			if (gpsBuf.lineStart >= gpsBuf.lineLen) {
				gpsBuf.lineStart = 0;  // 预先检查和重置索引，防止越界
			}
			
			uint8_t tmp = gpsBuf.line[gpsBuf.lineStart++];
			
			// 安全写入uart_line，确保不超过缓冲区上限
			if (uart_lineIndex < MAX_UART_LINE_SIZE - 1) {  // 保留一个字节给终止符
				uart_line[uart_lineIndex++] = tmp;
			} else {
				// 缓冲区已满，重置并记录错误
				uart_lineIndex = 0;
				printf("Error: uart_line buffer overflow detected\n");
			}
			
			// 循环缓冲区索引管理
			if(gpsBuf.lineStart >= gpsBuf.lineLen)
			{
				gpsBuf.lineStart = 0;
			}
			
			// 安全的缓冲区大小检查
			if(uart_lineIndex >= MAX_UART_LINE_SIZE) {
				uart_lineIndex = 0;
			}
			
			int useTsip = 0;
			if(!useTsip)
			{
				if(isUbx)
				{
					ubxLen--;
					if(ubxLen == 0)
					{
						doUbxPro(uart_line,uart_lineIndex);
						isUbx = 0;
						uart_lineIndex = 0;
					}
				}
				else
				{
					if(preOne == 0xB5 && tmp == 0x62)  //ubx msg
					{
						// 安全读取UBX消息长度，添加边界检查
						uint16_t len = 8;  // 默认最小长度
						uint16_t safeStart = gpsBuf.lineStart;
						
						// 检查是否有足够的空间读取长度字段
						if ((safeStart + 2) < gpsBuf.lineLen || 
						    (safeStart >= gpsBuf.lineLen && (safeStart + 2 - gpsBuf.lineLen) < gpsBuf.lineLen)) {
							// 使用安全方式读取2字节长度，避免直接指针操作
							uint8_t lenHi, lenLo;
							uint16_t readIdx = safeStart;
							
							lenLo = gpsBuf.line[readIdx++];
							if (readIdx >= gpsBuf.lineLen) readIdx = 0;
							
							lenHi = gpsBuf.line[readIdx++];
							if (readIdx >= gpsBuf.lineLen) readIdx = 0;
							
							len = (lenHi << 8) | lenLo;
							len += 8;  // 添加头部和校验和长度
							
							// 确保长度合理，避免过大的值
							if (len > MAX_UART_LINE_SIZE) {
								len = MAX_UART_LINE_SIZE;
							}
						}
						
						// 安全检查索引有效性
						if(uart_lineIndex >= 2)
						{
							uart_line[uart_lineIndex - 2] = 0;
							doGpsCmd(uart_line,uart_lineIndex);
							uart_line[0] = 0xB5;
							uart_line[1] = 0x62;
							uart_lineIndex = 2;
							ubxLen = len - 2;
							isUbx = 1;
						}
					}
					
					// 安全处理换行符
					if(preOne == 0x0D && tmp == 0x0A)
					{
						// 确保不越界写入终止符
						if (uart_lineIndex < MAX_UART_LINE_SIZE) {
							uart_line[uart_lineIndex] = 0;
							doGpsCmd(uart_line,uart_lineIndex);
						}
						uart_lineIndex = 0;
					}
					else if(tmp == '$')
					{
						if(uart_lineIndex > 4)
						{
							// 确保不越界写入终止符
							if (uart_lineIndex < MAX_UART_LINE_SIZE) {
								uart_line[uart_lineIndex] = 0;
								doGpsCmd(uart_line,uart_lineIndex);
							}
							uart_line[0] = '$';
							uart_lineIndex = 1;
						}
					}
				}
			}
			else
			{
				if(tmp == 0x03 && preOne == 0x10)
				{
					doTSip(uart_line, uart_lineIndex);
					uart_lineIndex = 0;
				}
			}
			preOne = tmp;
		}
		lastUpdate = HAL_GetTick();
	}
	
	// 安全重启UART接收，添加额外的状态检查
	if((HAL_GetTick() - lastUpdate > 20000) || huart6.RxState == HAL_UART_STATE_READY)
	{
		lastUpdate = HAL_GetTick();
		DBGI("bef uart status gst=%d err=%d rxstus=%d\n", huart6.gState, huart6.ErrorCode, huart6.RxState);
		
		// 添加额外的错误检查
		if (huart6.gState == HAL_UART_STATE_READY && huart6.ErrorCode == HAL_UART_ERROR_NONE) {
			HAL_UARTEx_ReceiveToIdle_DMA(&huart6, gpsBuf.dmabuf, gpsBuf.dmabufLen);
		}
		
		printf("uart status gst=%d err=%d rxstus=%d\n", huart6.gState, huart6.ErrorCode, huart6.RxState);
		DBG("RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR\n");
	}
}

void user_runloop(void) 
{
	static uint32_t tick1s = 0;
  HAL_IWDG_Refresh(&hiwdg);
  TDC_Task();
	uint32_t tick = HAL_GetTick();
	if((tick - tick1s) > 1000)
	{
		tick1s = tick;
		//HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adcBuf, 256);
		float data_float = (g_mcuTemp/16384.0f)*3.3f;		//计算电压值
	  float temp  = (data_float-0.771f)/0.0043f + 30.7f; 
		float tempex = tmp75_read();
		g_ctlStatus.temp = tempex;
		g_ctlStatus.mcuTemp = temp;
		//printf("mcu temp = %d %.2f %.2f\n", g_mcuTemp, temp, tempex);
	}
}

/*void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart)
{
	UartBuf *uartBuf = &gpsBuf;
	if(huart == &huart1)
	{
		uartBuf = &cmdBuf;
	}
	HAL_UARTEx_RxEventCallback(huart, uartBuf->dmabufLen/2);
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	UartBuf *uartBuf = &gpsBuf;
	if(huart == &huart1)
	{
		uartBuf = &cmdBuf;
	}
	HAL_UARTEx_RxEventCallback(huart, uartBuf->dmabufLen);
}*/

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	uint16_t i = 0;
	uint8_t reType = huart->RxEventType;
	UartBuf *uartBuf = &gpsBuf;
	if(huart == &huart1)
	{
		uartBuf = &cmdBuf;
	}
	//__disable_irq();
	for(i=uartBuf->readIdx;i<Size;i++)
	{
		uartBuf->line[uartBuf->lineEnd++] = uartBuf->dmabuf[i];
		//printf("%c", uartBuf->dmabuf[i]);
		if(uartBuf->lineEnd >= uartBuf->lineLen)
		{
			uartBuf->lineEnd = 0;
		}
		if(uartBuf->lineEnd == uartBuf->lineStart)
		{
			//printf("====================uart overflow %d i=%d end=%d\n", Size, i, uartBuf->lineEnd);
			break;
		}
	}
	//uint16_t oldIdx = uartBuf->readIdx;
	uartBuf->readIdx = Size;
	if(uartBuf->readIdx >= uartBuf->dmabufLen)
	{
		uartBuf->readIdx = 0;
	}
	//if(huart == &huart6)
	//	printf("P = %d t=%d s=%d e=%d rIdx=%d oldIdx=%d\n", Size, reType, uartBuf->lineStart, uartBuf->lineEnd, uartBuf->readIdx, oldIdx);
	//__enable_irq();
	BaseType_t needSch;
	if(UartTaskHandle)
	{
		vTaskNotifyGiveFromISR(UartTaskHandle, &needSch);
		portYIELD_FROM_ISR(needSch);
	}
}

void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
	if(huart == &huart1)
	{
		HAL_UARTEx_ReceiveToIdle_DMA(&huart1,cmdBuf.dmabuf,cmdBuf.dmabufLen);
	}
	else if(huart == &huart6)
	{
		HAL_UARTEx_ReceiveToIdle_DMA(&huart6,gpsBuf.dmabuf,gpsBuf.dmabufLen);
	}
}

static uint8_t adForTDC = 1;
static int32_t ad_min = 10000;
static int32_t ad_max = 0;

void ShowADMinMax(void)
{
	DBGI("min=%d max=%d full=%d\n", ad_min, ad_max, ad_max-ad_min);
}

uint32_t preValue = 0;
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
	static ADC_ChannelConfTypeDef sConfig = {0};
	static uint8_t tdcinit = 0;
	int32_t fullScal = g_Controller_config.fullscal;
	if(adForTDC)
	{
		HAL_GPIO_WritePin(DISCHARGE_GPIO_Port,DISCHARGE_Pin,GPIO_PIN_RESET);
		int32_t sum = 0;
		for(int i=0;i<64;i++)
		{
			sum+=adcBuf[i];
		}
		sum = sum >> 4;
		if(sum > ad_max) ad_max = sum;
		if(sum < ad_min) ad_min = sum;
		sum = sum - g_Controller_config.adcZero;
		int32_t offset = preValue - sum;
		int32_t of2 = offset;
		preValue = sum;
		if(offset>10000)
		{
			offset -= fullScal;
		}
		else if(offset < -10000)
		{
			offset += fullScal;
		}
		if(/*g_oc_status.controlCount >= 0 || */!ocxo_warm_ok)
		{
			if(ABS(offset)>5000)
				DBGI("TDC = %d, offset=%d of2=%d full=%d\n", sum, offset, of2, fullScal);
			else
				DBGI("TDC = %d, of=%d pps=%d\n", sum, offset, g_ppspre);
		}
		if(!tdcinit)
		{
			tdcinit = 1;
		}
		else
		{
			g_tdcOffset = offset;
			g_tdcValue = sum;
			g_tdcReady = 1;
		}
	  adForTDC = 0;
		sConfig.Channel = ADC_CHANNEL_TEMPSENSOR;
		sConfig.Rank = 1;
		sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
		HAL_ADC_ConfigChannel(&hadc1, &sConfig);
		HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adcBuf, 64);
	}
	else
	{
		uint32_t tmp = 0;
		for(int i=0;i<64;i++)
		{
			tmp += adcBuf[i];
		}
		g_mcuTemp = tmp >> 6;
		//printf("mcu tmp = %d\n", g_mcuTemp);
		HAL_GPIO_WritePin(DISCHARGE_GPIO_Port,DISCHARGE_Pin,GPIO_PIN_SET);
		sConfig.Channel = ADC_CHANNEL_2;
		sConfig.Rank = 1;
		sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
		HAL_ADC_ConfigChannel(&hadc1, &sConfig);
	}
	
	//printf("TTTTTTTTTTTTTTTTTTTTTTTadc result = %d\n", g_mcuTemp);
	//HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adcBuf, 256);
}


void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) {

	
}

/*void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
	totleCount++;
	printf("totole++\r\n");
}*/
static uint8_t errCount = 0;
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
	if(GPIO_Pin == GPIO_PIN_15) {
		uint32_t t = htim5.Instance->CNT;
		if(g_oc_status.needSyncPPS) 
		{
			htim5.Instance->CNT = 56;
			int32_t t = g_oc_status.preTdcValue >> 16;
			if((g_Controller_config.type == 2) && (t > 15000 || t < 1000))
			{
				htim9.Instance->CNT = htim9.Instance->ARR - 17;
				g_oc_status.offsetInvlid = 1;
				printf("offset adjust...\n");
			}
			//t = 45;
			g_oc_status.needSyncPPS = 0;
		}
		adForTDC = 1;
		if(g_Controller_config.type == 1)
		{
			HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adcBuf, 64);
		}
		g_ppsoff = g_ppspre - t;
		g_ppspre = t;
		if(t < 35 || t > 55)
		{
			//printf("&&& nsy %d\n", t);
			errCount++;
			if(errCount > 10)
			{
				errCount = 0;
				g_oc_status.needSyncPPS = 1;
				//printf("resync....\n");
			}
		}
		else {
			errCount = 0;
		}
	}
}
